package com.bestv.search.engine.command;

import com.bestv.search.common.cache.SystemCache;
import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.History;
import com.bestv.search.common.service.HistoryManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Node;

/**
 * @author Michael Wang
 */

// $Id: HistoryCommand.java 51 2012-03-15 08:45:54Z wbwang $
public class HistoryCommand {

    private static final int DEFAULT_HISTORY_LIMIT = 10;
    protected final Log log = LogFactory.getLog(getClass());
    private HistoryQueue queue;
    private HistoryManager historyManager;
    private SystemCache systemCache;

    public String history(Document doc) {
        Node userNode = doc.selectSingleNode("/request/userId");
        if (userNode == null || "".equals(userNode.getText().trim())) {
            log.error("History request must have a userId element.");
            return xmlPiece("1", "请求消息格式错误");
        }
        Node limitNode = doc.selectSingleNode("/request/limit");
        int limit = DEFAULT_HISTORY_LIMIT;
        if (limitNode != null && !"".equals(limitNode.getText().trim())) {
            try {
                limit = Integer.valueOf(limitNode.getText().trim());
            } catch (Exception e) {
                log.warn("Parse limit node to integer error!");
                limit = DEFAULT_HISTORY_LIMIT;
            }
        }
        return history(userNode.getText().trim(), limit);
    }

    private String history(String userId, int limit) {
        try {
            StringBuffer result = new StringBuffer(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><result><record><keyword>");
            String history = queue.getUserHistory(userId);
            if ("".equals(history)) {
                DataSourceKey key = DataSourceKeyUtil.convert(systemCache.getLocalDataSourceKey());
                History serializedHistory = historyManager.getHistoryByUserId(key, userId);
                if (serializedHistory != null) {
                    history = serializedHistory.getHistory();
                    queue.push(serializedHistory);
                }
            }
            if (history.indexOf("_") != -1) {
                String[] hisArr = history.split("_");
                int n = Math.min(hisArr.length, limit);
                for (int i = 0; i < n; i++) {
                    result.append(hisArr[i]).append(" ");
                }
            } else {
                result.append(history);
            }
            result.append("</keyword></record></result>");
            return result.toString();
        } catch (Exception e) {
            log.error("Error occured while searching index in memory.");
            e.printStackTrace();
            return xmlPiece("2", "内部错误");
        }
    }

    public void clear() {
        queue.clear();
    }

    public void lockQueue() {
        queue.setFirstLevelLock(true);
    }

    public void freeQueue() {
        queue.setFirstLevelLock(false);
    }

    private String xmlPiece(String code, String message) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><error><code>" + code + "</code><message>" + message
                + "</message></error>";
    }

    public HistoryQueue getQueue() {
        return queue;
    }

    public void setQueue(HistoryQueue queue) {
        this.queue = queue;
    }

    public HistoryManager getHistoryManager() {
        return historyManager;
    }

    public void setHistoryManager(HistoryManager historyManager) {
        this.historyManager = historyManager;
    }

    public SystemCache getSystemCache() {
        return systemCache;
    }

    public void setSystemCache(SystemCache systemCache) {
        this.systemCache = systemCache;
    }
}
